<?php

namespace frontend\modules\shop\controllers;
use common\components\Category;
use common\components\Upload;
use common\models\articlesite\ArticlesiteArticle;
use common\models\business\BusinessContract;
use common\models\business\BusinessCost;
use common\models\business\BusinessFarmers;
use common\models\business\BusinessInspection;
use common\models\business\BusinessPerson;
use common\models\business\BusinessPig;
use common\models\business\BusinessPigFile;
use common\models\business\BusinessVariety;
use common\models\business\NewBusinessInspectionData;
use common\models\business\NewBusinessInspectionField;
use common\models\shop\ShopGoods;
use common\models\shop\ShopGoodsCategory;
use common\models\shop\ShopSlide;
use common\models\sys\SysSetting;
use frontend\controllers\BaseMobileController;
use yii\db\Query;
use yii\helpers\ArrayHelper;
use yii\helpers\Url;
use yii\web\Response;

/**
 * Class SiteController
 * @package frontend\modules\business\controllers
 * 商城相关控制器
 */
class SiteController extends BaseMobileController
{


    public function actionPreIndex()
    {

        //取出推荐的商品
        $sql = "select thumb,id,displayorder from ".ShopGoods::tableName().' where (isrecommand=:isrecommand or isnew=:isnew or isdiscount=:isdiscount or istime-:istime)  and status=:status order by displayorder asc';

        $recommand = \Yii::$app->db->createCommand($sql)
            ->bindValues(
                [
                ':isrecommand'=>ShopGoods::RECOMMAND,
                ':isnew' => ShopGoods::ISNEW,
                ':isdiscount' => ShopGoods::DISCOUNT,
                ':istime' => ShopGoods::TIME,
                ':status'=>ShopGoods::STATUS_ACTIVE
                ])
            ->queryAll();

        foreach($recommand as $key => $row){
            $recommand[$key]['thumb'] = Upload::checkGetUrl($row['thumb']);
            $recommand[$key]['url'] = Url::to(['/shop/goods/detail', 'gid' => $row['id']]);
        }


        //取出顶部的图片
        $banner = Upload::checkGetUrl(SysSetting::getValue("shop_banner_img"));
        return $this->render('@template/mobile/shop_index.html',[
            'recommand' => $recommand?$recommand:[],
            'banner' => $banner,
            'jsonrecommand' => \GuzzleHttp\json_encode($recommand),
        ]);

    }


    /**
     * @return string
     * 商城首页
     */
    public function actionIndex()
    {

        $slids = ShopSlide::find()->select('picture')->where('status=:status and type=:type',[':status'=>ShopSlide::ACTIVE_STATUS,':type'=>ShopSlide::TYPE_SHOP])->asArray()->all();
        $banner = [];
        foreach ($slids as $slid => $row) {
            $banner[] = Upload::checkGetUrl($row['picture']);
        }
        
        $cate = ShopGoodsCategory::find()->select('name,id,thumb,parentid')
            ->where('enabled=:status and parentid!=0',[':status'=>ShopGoodsCategory::ENABLE_ACTIVE])->orderBy('displayorder desc')->asArray()->all();
        foreach ($cate as $key => $row) {
            if(mb_strlen($row['name'])>5) {
                $cate[$key]['name'] = mb_substr($row['name'],0,4);
            }
            $cate[$key]['url'] = Url::to(['/shop/goods/list', 'cid' => $row['id']]);
            $cate[$key]['thumb'] = Upload::checkGetUrl($row['thumb']);
        }
//        $cate = Category::getTree($cate);




        //热卖
        $pwd = \Yii::$app->request->get("pawd");
        if(empty($pwd)){
            $goods = ShopGoods::findHot(50);
            foreach ($goods as $key => $row){
                if(mb_strlen($row['title'])>15){
                    $goods[$key]['title'] = mb_substr($row['title'],0,7).'...';
                }
            }
        }else{
            $goods = ShopGoods::find()->select('unit,id,weight,thumb as img,description as text,timeend,title,productprice as price,total as nums,originalprice as o_price')
                ->where('status=:status and title like :pwd',
                    [':status'=>ShopGoods::STATUS_ACTIVE,':pwd'=>'%'.$pwd.'%']
                )
                ->orderBy('displayorder asc')
                ->asArray()
                ->all();
            foreach ($goods  as $key => $row)
            {
                $goods[$key]['title'] = mb_substr($row['title'],0,7).'...';
                $goods[$key]['img'] = Upload::checkGetUrl($row['img']);
                $goods[$key]['url'] = Url::to(['/shop/goods/detail','gid'=>$row['id']]);
            }

        }


        //取出限时购
        $timegoods = ShopGoods::findTime();

        //取出推荐
        $commandgoods = ShopGoods::findCommand();

        //取出 新品
        $newgoods = ShopGoods::findNew();

        //预售猪肉
        $pregoods = ShopGoods::findPre();




        return $this->render('@template/mobile/index_new.html',[
            'slids' => \GuzzleHttp\json_encode($banner),
            'cate' => $cate,
            'goods' => \GuzzleHttp\json_encode($goods),
            'pregoods' => \GuzzleHttp\json_encode($pregoods),
            'timegoods' => \GuzzleHttp\json_encode($timegoods),
            'newgoods' => \GuzzleHttp\json_encode($newgoods),
            'commandgoods' => \GuzzleHttp\json_encode($commandgoods),
            'oldtimegoods' => $timegoods,
            'oldpregoods' => $pregoods,
            'oldnewgoods' => $newgoods,
            'oldcommandgoods' => $commandgoods
        ]);
    }



/*    public function actionIndex()
    {

        $slids = ShopSlide::find()->select('picture')->where('status=:status and type=:type',[':status'=>ShopSlide::ACTIVE_STATUS,':type'=>ShopSlide::TYPE_SHOP])->asArray()->all();
        $banner = [];
        foreach ($slids as $slid => $row) {
            $banner[] = Upload::checkGetUrl($row['picture']);
        }

        $cate = ShopGoodsCategory::find()->select('name,id,parentid')->where('enabled=:status',[':status'=>ShopGoodsCategory::ENABLE_ACTIVE])->orderBy('displayorder desc')->asArray()->all();
        foreach ($cate as $key => $row)
        {
            $cate[$key]['url'] = Url::to(['/shop/goods/list','cid'=>$row['id']]);
        }

        $cate = Category::getTree($cate);


        //热卖
        $goods = ShopGoods::findHot();
        foreach ($goods as $key => $row){
            if(mb_strlen($row['title'])>7){
                $goods[$key]['title'] = mb_substr($row['title'],0,7).'...';
            }
        }


        //取出限时购
        $timegoods = ShopGoods::findTime();

        //取出推荐
        $commandgoods = ShopGoods::findCommand();

        //取出 新品
        $newgoods = ShopGoods::findNew();

        //预售猪肉
        $pregoods = ShopGoods::findPre();




        return $this->render('@template/mobile/index.html',[
            'slids' => \GuzzleHttp\json_encode($banner),
            'cate' => \GuzzleHttp\json_encode($cate),
            'goods' => \GuzzleHttp\json_encode($goods),
            'pregoods' => \GuzzleHttp\json_encode($pregoods),
            'timegoods' => \GuzzleHttp\json_encode($timegoods),
            'newgoods' => \GuzzleHttp\json_encode($newgoods),
            'commandgoods' => \GuzzleHttp\json_encode($commandgoods),
            'oldtimegoods' => $timegoods,
            'oldpregoods' => $pregoods,
            'oldnewgoods' => $newgoods,
            'oldcommandgoods' => $commandgoods
        ]);
    }*/


    /**
     *商城加载更多
     */
    public function actionLoadMore()
    {
        $pindex = \Yii::$app->request->post('pindex');
        $pindex = $pindex?$pindex:1;
        $pagesize = 10;
        //普通猪肉
//        $goods = ShopGoods::find()->select('weight,id,thumb as img,id,title,originalprice as o_price,productprice as price,total as nums')
//            ->where('ishot=:hot',[':hot'=>ShopGoods::HOT])
//            ->limit($pagesize)->offset(($pindex-1)*$pagesize)
//            ->asArray()
//            ->all();
        $goods = ShopGoods::findHot(1);
        foreach ($goods as $key => $row)
        {
            $goods[$key]['img'] = Upload::checkGetUrl($row['img']);
            $goods[$key]['url'] = Url::to(['/shop/goods/detail','gid'=>$row['id']]);
        }

        \Yii::$app->response->format = Response::FORMAT_JSON;

        return $goods;
    }



    /**
     * @return string
     * 源头追溯
     */
    public function actionFrom()
    {
        $pigid = \Yii::$app->request->get('pigid');
        if(empty($pigid)){
            return $this->error('sorry ，溯源信息走失了...');
        }

        //取出仔猪信息
        $pig = (new Query())->from(BusinessPig::tableName().' as p')
            ->select('f.id as fid,f.introducer as pid,p.slaughter,p.planout,p.video,pf.name as title,p.id,p.no as number,p.status,p.batch,p.no,p.photo,p.batch,p.intime,p.headpersonid,p.headperson as owner,liveryname as operator,p.killplace as slaughterhouse,v.title as type,f.address,pf.father as f_no,pf.mathor as m_no,c.partyA,c.no as contract_no')
            ->addSelect('pf.matherphoto as m_img,fatherphoto as f_img,f.pighousephoto')
            ->leftJoin(BusinessFarmers::tableName().' as f','p.livery=f.id')
            ->leftJoin(BusinessVariety::tableName().' as v','v.id=p.varietyid')
            ->leftJoin(BusinessPigFile::tableName().' as pf','pf.id=p.fileid')
            ->leftJoin(BusinessContract::tableName().' as c','c.id=pf.constract_id')
            ->where('p.no=:id',[':id'=>$pigid])
            ->one();
        if(!$pig){
            return $this->error('你查看的仔猪不存在');
        }


        //处理数据
        $pig['status'] = BusinessPig::$statues[$pig['status']];
        $pig['m_img'] = Upload::checkGetUrl($pig['m_img']);
        $pig['f_img'] = Upload::checkGetUrl($pig['f_img']);
        $pig['surroundings'] = Upload::checkGetUrl($pig['pighousephoto'],true);

        $pig['video'] = Upload::checkGetUrl($pig['video'],true,'video');

//        $pig['period'] = intval((time()-$pig['intime'])/3600*24).'天';
        $pig['intime'] = date('Y-m-d',$pig['intime']);
        $pig['planout'] = date('Y-m-d',$pig['planout']);
        //取出巡检记录
        $records = BusinessInspection::find()->select('id,createtime,business_person')->where('pigid=:pigid and status=:status',[':pigid'=>$pig['id'],':status'=>BusinessInspection::STATUS_PASSED])->asArray()->all();
        if($records){
            foreach ($records as $key => $row)
            {
                $records[$key]['title'] = date('Y-m-d',$row['createtime']);
                $records[$key]['no'] = $key+1;
                $records[$key]['who'] = $row['business_person'];
                $records[$key]['url'] = \yii\helpers\Url::to(['/shop/site/new-from-detail','recordid'=>$row['id']]);
            }
        }
        $pig['records'] = $records;


        //取出成本
        $costs = BusinessCost::find()
            ->select('type as title,price,description as content')
            ->where('pigid=:pigid',[':pigid'=>$pig['id']])
            ->asArray()
            ->all();
        $pig['costs'] = $costs;
        $pig['totalcost'] = array_sum(ArrayHelper::getColumn($costs,'price'));

        //取出banner
        $banner = Upload::checkGetUrl($pig['photo'],true);


        //判断是否是巡检员
        $checkperson = (new Query())->select('person.id')
            ->from(BusinessPerson::tableName().' as person')
            ->leftJoin(BusinessPig::tableName().' as pig','person.id=pig.headpersonid')
            ->where('person.openid=:openid and person.status=:status and pig.id=:pigid',[':openid'=>$this->user['openid'],':status'=>BusinessPerson::STATUS_JOB,':pigid'=>$pig['id']])
            ->scalar();

        if($pig['headpersonid'] == 27){
            $checkperson = 27;
        }
        return $this->render('@template/mobile/from.html',[
            'detail' => \GuzzleHttp\json_encode($pig),
            'pigid' => $pig['id'],
            'pigno' => $pig['no'],
            'pig' => $pig,
            'banner' => \GuzzleHttp\json_encode($banner),
            'checkperson' => $checkperson,
        ]);
    }


    /**
     * @param $recordid
     * @return string
     * 巡检详情
     */
    public function actionFromDetail($recordid)
    {
        $pig = (new Query())->from(BusinessInspection::tableName().' as i')
            ->select('id,cleanpen,disinfection,urine,pen_temperature,urine,healthy as health,healthy_desc as healthinfo,situation,feed_photo as f_imgs,feed as feed,feed_desc,pigpen as pighouse,pigpen_desc as pighouseinfo,pigpen_photo as p_imgs,pigphoto as s_imgs')
            ->addSelect('width,height,length,weight,activelevel,haircolor,foodintake,shit,temperature,breath')
            ->where('i.id=:id',[':id'=>$recordid])
            ->one();


        $pig['situationinfo'] = [
            '身高' => $pig['height'].'cm',
            '总长' => $pig['length'].'cm',
            '肩高' => $pig['width'].'cm',
            '体重' => $pig['weight'].'kg',
            '精神' => $pig['activelevel'],
            '毛色' => $pig['haircolor'],
            '食量' => $pig['foodintake'],
            '大便' => $pig['shit'],
            '体温' => $pig['temperature'].'℃',
            '呼吸' => $pig['breath'],
            '清圈' => $pig['cleanpen'].'次/周',
            '消毒' => $pig['disinfection'].'次/周',
            '尿' => $pig['urine'],
            '环境温度' => $pig['pen_temperature'].'℃',
        ];

        $pig['s_imgs'] = Upload::checkGetUrl($pig['s_imgs'],true);
        $pig['p_imgs'] = Upload::checkGetUrl($pig['p_imgs'],true);
        $pig['f_imgs'] = Upload::checkGetUrl($pig['f_imgs'],true);

        return $this->render('@template/mobile/businessman_inspection_detail.html',[
            'detail' => \GuzzleHttp\json_encode($pig)
        ]);
//        return $this->render('@template/mobile/fromdetail.html',[
//            'pig' => \GuzzleHttp\json_encode($pig),
//        ]);

    }


    public function actionNewFromDetail($recordid)
    {
        $detail= (new Query())->select('*')->from(NewBusinessInspectionData::tableName())
            ->where('inspectionid=:id',[':id'=>$recordid])
            ->indexBy('fieldname')
            ->all();

        $fields = NewBusinessInspectionField::allField();

        foreach ($detail as $key => $value){
            if($value['fieldtype'] == 'image'){
                $ndetail['image'][] = Upload::checkGetUrl($value['val'],true);
            }else  if($value['fieldtype'] == 'textarea') {
                $ndetail['textarea'][] = $value;
            }else{
                $ndetail['input'][] = $value;
            }
        }

        $detail['situationinfo'] = $ndetail;



        return $this->render('@template/mobile/businessman_inspection_detail.html',[
            'detail' => \GuzzleHttp\json_encode($detail)
        ]);
//        return $this->render('@template/mobile/fromdetail.html',[
//            'pig' => \GuzzleHttp\json_encode($pig),
//        ]);

    }


    /**
     * @return array|\yii\db\ActiveRecord[]
     * 搜索商品
     */
    public function actionSearchGoods()
    {
        $kwd = \Yii::$app->request->post('keywords');
        $goods = ShopGoods::find()->select('unit,id,weight,thumb as img,id,title,originalprice as o_price,productprice as price,total as nums')
            ->where('status=:status and title like :kwd',[':kwd'=>"%$kwd%",':status'=>ShopGoods::STATUS_ACTIVE])
            ->asArray()
            ->all();

        foreach ($goods as $key => $row)
        {
            $goods[$key]['img'] = Upload::checkGetUrl($row['img']);
            $goods[$key]['url'] = Url::to(['/shop/goods/detail','gid'=>$row['id']]);
        }

        \Yii::$app->response->format = Response::FORMAT_JSON;

        return $goods?$goods:$this->jsonMsg('啊哦，还没有对应的商品',1);
    }


    /**
     * 代养农户详情
     */
    public function actionLiveryDetail()
    {
        $id = \Yii::$app->request->get("id");

        $detail = (new Query())->select('address,name,phone,descripation,identity_photo,photo')->from(BusinessFarmers::tableName())->where(['id'=>$id])->one();

        $detail['identity_photo'] = Upload::checkGetUrl($detail['identity_photo'],false,'identity_photo');
        $detail['photo'] = Upload::checkGetUrl($detail['photo'],false,'photo');

        return $this->render('@template/mobile/liverydetail.html',[
            'detail' => \GuzzleHttp\json_encode($detail)
        ]);

    }


    /**
     * 业务员详情
     */
    public function actionPersonDetail()
    {
        $id = \Yii::$app->request->get("id");

        $detail = (new Query())->select('name as pname,phone as pphone,descripation as pdescripation,identity_img')->from(BusinessPerson::tableName())->where(['id'=>$id])->one();

        $detail['identity_img'] = Upload::checkGetUrl($detail['identity_img'],false,'identity_img');


        return $this->render('@template/mobile/persondetail.html',[
            'detail' => \GuzzleHttp\json_encode($detail)
        ]);

    }


















}
